package org.hashdb.client.view;

import org.hashdb.client.console.AppConsoleReader;
import org.hashdb.client.manager.NioAppContext;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * Date: 2024/1/21 15:09
 *
 * @author huanyuMake-pecdle
 * @version 0.0.1
 */
public class NioIndexPage extends CmdArgsPage {

    private static NioIndexPage instance;

    public static NioIndexPage instance() {
        if (instance == null) {
            instance = new NioIndexPage();
        }
        return instance;
    }

    private NioIndexPage() {
    }

    @Override
    void show(Map<String, String> options) throws IOException {
        AppConsoleReader appConsoleReader;
        try (var bootstrapReader = AppConsoleReader.bootstrap()) {
            bootstrapReader.messageLn("Welcome to use HashDB-CLI!");
            var outputEncoding = Objects.requireNonNullElse(config.getOutputEncoding(), bootstrapReader.queryOutputCharset());
            appConsoleReader = AppConsoleReader.newConsoleReader(outputEncoding);
        }
        NioAppContext ctx = NioAppContext.singletonIfNeeded(appConsoleReader);
//        appConsoleReader.messageLn("before connected");
        ctx.client().tryConnect().join();
//        appConsoleReader.messageLn("start handle cmd");
        ctx.dispatcher().startPublishFormReader();
        System.out.println("thread '" + Thread.currentThread() + "' exit");
//        ctx.client().tryConnect().thenRunAsync(() -> {
//        }, AsyncService.service());
    }
}
